<script setup lang="ts">
import { computed, nextTick, onUnmounted, ref, watch } from 'vue'

interface FilterParams {
  name?: string
  address?: string
  enable?: boolean
  common?: boolean
  page?: number
  limit?: number
  [key: string]: any
}

interface Props {
  /** 筛选参数 */
  modelValue?: FilterParams
  /** 默认是否展开 */
  defaultExpanded?: boolean
}

// 定义组件名称
defineOptions({
  name: 'WarehouseFilter',
})

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({}),
  defaultExpanded: false,
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: FilterParams): void
  (e: 'search'): void
  (e: 'reset'): void
}>()

// 状态管理
const showFilterPanel = ref(props.defaultExpanded)

// 下拉选项数据
const enableOptions = [
  { label: '启用', value: true },
  { label: '禁用', value: false },
]

const commonOptions = [
  { label: '公共仓库', value: true },
  { label: '私有仓库', value: false },
]

// 内部筛选参数 - 使用ref实现
const internalFilters = ref<FilterParams>({
  name: '',
  address: '',
  enable: null,
  common: null,
  page: 1,
  limit: 10,
  ...props.modelValue,
})

// 监听外部参数变化，只在初始化时同步
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      // 只在外部参数有值且内部参数为空时同步
      const current = internalFilters.value
      if (!current.name && !current.address) {
        internalFilters.value = {
          ...internalFilters.value,
          ...newVal,
        }
      }
    }
  },
  { immediate: true },
)

// 计算属性
const hasActiveFilters = computed(() => {
  const filters = internalFilters.value
  return !!(filters.name || filters.address || filters.enable !== null || filters.common !== null)
})

// 事件处理
function toggleFilterPanel() {
  showFilterPanel.value = !showFilterPanel.value
}

function handleSearch() {
  console.log('触发搜索，当前筛选条件:', internalFilters.value)
  // 同步参数到父组件
  emit('update:modelValue', { ...internalFilters.value })
  emit('search')
}

function handleEnableChange(value: any) {
  console.log('启用状态变化，原始值:', value) // 调试日志
  console.log('启用状态变化，值类型:', typeof value) // 调试日志
  console.log('启用状态变化，值内容:', JSON.stringify(value)) // 调试日志

  // 处理 wd-picker 返回的值
  let enableValue: boolean | null = null

  // wd-picker 通常返回数组，第一个元素是选中的值
  if (Array.isArray(value) && value.length > 0) {
    enableValue = value[0]
  } else if (value && typeof value === 'object' && value.value !== undefined) {
    enableValue = value.value
  } else if (typeof value === 'boolean') {
    enableValue = value
  } else if (typeof value === 'string') {
    if (value === 'true') enableValue = true
    else if (value === 'false') enableValue = false
  }

  console.log('处理后的启用状态值:', enableValue) // 调试日志

  // 直接更新内部状态
  internalFilters.value.enable = enableValue

  // 直接同步到父组件
  emit('update:modelValue', { ...internalFilters.value })

  // 不自动触发搜索，让用户手动点击搜索按钮
  console.log('启用状态已更新，等待用户手动搜索') // 调试日志
}

function handleCommonChange(value: any) {
  console.log('仓库类型变化，原始值:', value) // 调试日志
  console.log('仓库类型变化，值类型:', typeof value) // 调试日志
  console.log('仓库类型变化，值内容:', JSON.stringify(value)) // 调试日志

  // 处理 wd-picker 返回的值
  let commonValue: boolean | null = null

  // wd-picker 通常返回数组，第一个元素是选中的值
  if (Array.isArray(value) && value.length > 0) {
    commonValue = value[0]
  } else if (value && typeof value === 'object' && value.value !== undefined) {
    commonValue = value.value
  } else if (typeof value === 'boolean') {
    commonValue = value
  } else if (typeof value === 'string') {
    if (value === 'true') commonValue = true
    else if (value === 'false') commonValue = false
  }

  console.log('处理后的仓库类型值:', commonValue) // 调试日志

  // 直接更新内部状态
  internalFilters.value.common = commonValue

  // 直接同步到父组件
  emit('update:modelValue', { ...internalFilters.value })

  // 不自动触发搜索，让用户手动点击搜索按钮
  console.log('仓库类型已更新，等待用户手动搜索') // 调试日志
}

function handleNameChange() {
  console.log('名称输入变化:', internalFilters.value.name) // 调试日志
  // 输入框变化时延迟触发搜索，避免频繁请求
  clearTimeout((window as any).nameSearchTimer)
  ;(window as any).nameSearchTimer = setTimeout(() => {
    console.log('名称搜索触发，值:', internalFilters.value.name) // 调试日志
    // 同步参数到父组件
    emit('update:modelValue', { ...internalFilters.value })
    emit('search')
  }, 500)
}

function handleAddressChange() {
  console.log('地址输入变化:', internalFilters.value.address) // 调试日志
  // 输入框变化时延迟触发搜索，避免频繁请求
  clearTimeout((window as any).addressSearchTimer)
  ;(window as any).addressSearchTimer = setTimeout(() => {
    console.log('地址搜索触发，值:', internalFilters.value.address) // 调试日志
    // 同步参数到父组件
    emit('update:modelValue', { ...internalFilters.value })
    emit('search')
  }, 500)
}

function clearNameSearch() {
  console.log('清除名称搜索') // 调试日志
  internalFilters.value.name = ''
  // 直接同步到父组件
  emit('update:modelValue', { ...internalFilters.value })
  emit('search')
}

function clearAddressSearch() {
  console.log('清除地址搜索') // 调试日志
  internalFilters.value.address = ''
  // 直接同步到父组件
  emit('update:modelValue', { ...internalFilters.value })
  emit('search')
}

function resetFilters() {
  console.log('重置筛选条件') // 调试日志
  internalFilters.value = {
    name: '',
    address: '',
    enable: null,
    common: null,
    page: 1,
    limit: 10,
  }
  // 直接同步到父组件
  emit('update:modelValue', { ...internalFilters.value })
  emit('reset')
}

// 获取显示文本
function getEnableText() {
  if (internalFilters.value.enable === true) return '启用'
  if (internalFilters.value.enable === false) return '禁用'
  return ''
}

function getCommonText() {
  if (internalFilters.value.common === true) return '公共仓库'
  if (internalFilters.value.common === false) return '私有仓库'
  return ''
}

// 组件卸载时清理定时器
onUnmounted(() => {
  clearTimeout((window as any).nameSearchTimer)
  clearTimeout((window as any).addressSearchTimer)
})

// 暴露方法给父组件
defineExpose({
  resetFilters,
  getFilters: () => internalFilters.value,
  setFilters: (filters: FilterParams) => {
    emit('update:modelValue', { ...internalFilters.value, ...filters })
  },
  togglePanel: toggleFilterPanel,
})
</script>

<template>
  <view class="warehouse-filter">
    <!-- 筛选面板头部 -->
    <view class="filter-header" @click="toggleFilterPanel">
      <view class="filter-header-left">
        <wd-icon name="filter" size="16px" color="#007AFF" />
        <text class="filter-title">筛选条件</text>
        <view v-if="hasActiveFilters" class="filter-active-dot" />
      </view>
      <view class="filter-header-right">
        <wd-button type="text" size="small" class="reset-button" @click.stop="resetFilters">
          重置
        </wd-button>
        <wd-icon
          :name="showFilterPanel ? 'arrow-up' : 'arrow-down'"
          size="16px"
          color="#8E8E93"
          class="collapse-icon"
        />
      </view>
    </view>

    <!-- 筛选面板内容 -->
    <view v-show="showFilterPanel" class="filter-content">
      <!-- 仓库名称搜索 -->
      <view class="filter-row">
        <view class="filter-item">
          <view class="search-input-wrapper">
            <view class="integrated-search-container">
              <view class="search-icon-section">
                <wd-icon name="search" size="16px" color="#8E8E93" />
              </view>
              <view class="search-divider" />
              <view class="search-input-section">
                <input
                  v-model="internalFilters.name"
                  placeholder="请输入仓库名称"
                  class="search-input"
                  @input="handleNameChange"
                  @keydown.enter="handleSearch"
                />
                <view v-if="internalFilters.name" class="clear-button" @click="clearNameSearch">
                  <wd-icon name="close-circle-fill" size="16px" color="#C7C7CC" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 仓库地址搜索 -->
      <view class="filter-row">
        <view class="filter-item">
          <view class="search-input-wrapper">
            <view class="integrated-search-container">
              <view class="search-icon-section">
                <wd-icon name="location" size="16px" color="#8E8E93" />
              </view>
              <view class="search-divider" />
              <view class="search-input-section">
                <input
                  v-model="internalFilters.address"
                  placeholder="请输入仓库地址"
                  class="search-input"
                  @input="handleAddressChange"
                  @keydown.enter="handleSearch"
                />
                <view
                  v-if="internalFilters.address"
                  class="clear-button"
                  @click="clearAddressSearch"
                >
                  <wd-icon name="close-circle-fill" size="16px" color="#C7C7CC" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 状态和类型筛选 -->
      <view class="filter-row">
        <view class="filter-group">
          <!-- 启用状态筛选 -->
          <view class="filter-item">
            <view class="filter-label">
              <wd-icon name="check-circle" size="14px" color="#007AFF" />
              <text class="label-text">启用状态</text>
            </view>
            <view class="picker-wrapper">
              <wd-picker
                :model-value="internalFilters.enable === null ? '' : String(internalFilters.enable)"
                :columns="[enableOptions]"
                placeholder="请选择状态"
                @confirm="handleEnableChange"
              >
                <view class="picker-trigger">
                  <text class="picker-text">
                    {{ getEnableText() || '请选择状态' }}
                  </text>
                  <wd-icon name="arrow-down" size="12px" color="#8E8E93" />
                </view>
              </wd-picker>
            </view>
          </view>

          <!-- 仓库类型筛选 -->
          <view class="filter-item">
            <view class="filter-label">
              <wd-icon name="share" size="14px" color="#007AFF" />
              <text class="label-text">仓库类型</text>
            </view>
            <view class="picker-wrapper">
              <wd-picker
                :model-value="internalFilters.common === null ? '' : String(internalFilters.common)"
                :columns="[commonOptions]"
                placeholder="请选择类型"
                @confirm="handleCommonChange"
              >
                <view class="picker-trigger">
                  <text class="picker-text">
                    {{ getCommonText() || '请选择类型' }}
                  </text>
                  <wd-icon name="arrow-down" size="12px" color="#8E8E93" />
                </view>
              </wd-picker>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索按钮 -->
      <view class="filter-actions">
        <wd-button type="primary" class="search-button" @click="handleSearch">
          <wd-icon name="search" size="16px" />
          <text>搜索</text>
        </wd-button>
        <wd-button class="reset-all-button" @click="resetFilters">
          <wd-icon name="refresh" size="16px" />
          <text>重置</text>
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// Apple设计系统变量
$system-blue: #007aff;
$system-red: #ff3b30;
$system-gray: #8e8e93;
$label-primary: #000000;
$label-secondary: rgba(60, 60, 67, 0.6);
$background-primary: #ffffff;
$background-secondary: #f2f2f7;
$separator: rgba(60, 60, 67, 0.36);

.warehouse-filter {
  background: $background-primary;
  border-radius: 16px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.1);

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: rgba(0, 122, 255, 0.05);
    border-bottom: 1px solid rgba(0, 122, 255, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;

    &:active {
      background: rgba(0, 122, 255, 0.1);
    }

    .filter-header-left {
      display: flex;
      align-items: center;
      gap: 10px;
      position: relative;

      .filter-title {
        font-size: 17px;
        font-weight: 600;
        color: $label-primary;
        letter-spacing: -0.2px;
      }

      .filter-active-dot {
        width: 8px;
        height: 8px;
        background: linear-gradient(45deg, $system-blue, #34c759);
        border-radius: 50%;
        margin-left: 8px;
        box-shadow: 0 2px 4px rgba(0, 122, 255, 0.3);
        animation: pulse 2s infinite;

        @keyframes pulse {
          0%,
          100% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.2);
            opacity: 0.8;
          }
        }
      }
    }

    .filter-header-right {
      display: flex;
      align-items: center;
      gap: 12px;

      .reset-button {
        padding: 4px 12px;
        background: linear-gradient(135deg, rgba(255, 59, 48, 0.1) 0%, rgba(255, 149, 0, 0.1) 100%);
        border: 1px solid rgba(255, 59, 48, 0.2);
        border-radius: 14px;
        color: $system-red;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.2s ease;

        &:active {
          background: linear-gradient(
            135deg,
            rgba(255, 59, 48, 0.2) 0%,
            rgba(255, 149, 0, 0.2) 100%
          );
          transform: scale(0.95);
        }
      }

      .collapse-icon {
        transition: all 0.3s ease;
      }
    }
  }

  .filter-content {
    padding: 20px;
    animation: filterExpand 0.3s ease;

    @keyframes filterExpand {
      from {
        opacity: 0;
        max-height: 0;
      }
      to {
        opacity: 1;
        max-height: 500px;
      }
    }
  }

  .filter-row {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .filter-item {
      .search-input-wrapper {
        .integrated-search-container {
          display: flex;
          align-items: stretch;
          background: $background-primary;
          border: 2px solid rgba(0, 122, 255, 0.1);
          border-radius: 16px;
          overflow: hidden;
          transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

          &:hover {
            border-color: rgba(0, 122, 255, 0.2);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
          }

          &:focus-within {
            border-color: $system-blue;
            box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.1);
          }

          .search-icon-section {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 14px 16px;
            background: linear-gradient(
              135deg,
              rgba(0, 122, 255, 0.05) 0%,
              rgba(52, 199, 89, 0.03) 100%
            );
            border-right: 1px solid rgba(0, 122, 255, 0.1);
            min-width: 60px;
          }

          .search-divider {
            width: 1px;
            background: linear-gradient(
              180deg,
              transparent 0%,
              rgba(0, 122, 255, 0.2) 50%,
              transparent 100%
            );
            margin: 8px 0;
          }

          .search-input-section {
            flex: 1;
            display: flex;
            align-items: center;
            padding: 0 16px;
            gap: 12px;
            position: relative;

            .search-input {
              flex: 1;
              border: none;
              outline: none;
              font-size: 16px;
              color: $label-primary;
              background: transparent;
              padding: 14px 0;
              font-weight: 400;
              letter-spacing: -0.1px;

              &::placeholder {
                color: rgba(142, 142, 147, 0.8);
                font-weight: 400;
              }

              &:focus {
                &::placeholder {
                  opacity: 0.5;
                }
              }
            }

            .clear-button {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 24px;
              height: 24px;
              border-radius: 12px;
              cursor: pointer;
              transition: all 0.2s ease;
              flex-shrink: 0;

              &:active {
                transform: scale(0.9);
                background: rgba(199, 199, 204, 0.2);
              }
            }
          }
        }
      }
    }

    .filter-group {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;

      .filter-item {
        .filter-label {
          display: flex;
          align-items: center;
          gap: 6px;
          margin-bottom: 8px;

          .label-text {
            font-size: 14px;
            font-weight: 600;
            color: $label-primary;
          }
        }

        .picker-wrapper {
          .picker-trigger {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 16px;
            background: $background-primary;
            border: 2px solid rgba(0, 122, 255, 0.1);
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              border-color: rgba(0, 122, 255, 0.2);
              background: rgba(0, 122, 255, 0.02);
            }

            &:active {
              transform: scale(0.98);
            }

            .picker-text {
              font-size: 14px;
              color: $label-primary;
              font-weight: 500;

              &:empty::before {
                content: attr(placeholder);
                color: rgba(142, 142, 147, 0.8);
              }
            }
          }
        }
      }
    }
  }

  .filter-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid rgba(0, 122, 255, 0.1);

    .search-button {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 20px;
      background: linear-gradient(135deg, $system-blue 0%, #5ac8fa 100%);
      border: none;
      border-radius: 12px;
      color: white;
      font-size: 15px;
      font-weight: 600;
      transition: all 0.3s ease;
      box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);

      &:active {
        transform: scale(0.95);
        box-shadow: 0 2px 8px rgba(0, 122, 255, 0.4);
      }
    }

    .reset-all-button {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 20px;
      background: linear-gradient(
        135deg,
        rgba(142, 142, 147, 0.1) 0%,
        rgba(199, 199, 204, 0.1) 100%
      );
      border: 2px solid rgba(142, 142, 147, 0.2);
      border-radius: 12px;
      color: $system-gray;
      font-size: 15px;
      font-weight: 600;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: linear-gradient(
          135deg,
          rgba(142, 142, 147, 0.2) 0%,
          rgba(199, 199, 204, 0.2) 100%
        );
      }
    }
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .warehouse-filter {
    .filter-content {
      padding: 16px;
    }

    .filter-row {
      .filter-group {
        grid-template-columns: 1fr;
        gap: 12px;
      }
    }

    .filter-actions {
      flex-direction: column;
      gap: 8px;
    }
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .warehouse-filter {
    background: #2c2c2e;

    .filter-header {
      background: rgba(0, 122, 255, 0.15);
      border-bottom-color: rgba(0, 122, 255, 0.2);
    }

    .filter-row {
      .filter-item {
        .search-input-wrapper {
          .integrated-search-container {
            background: #2c2c2e;

            .search-input-section {
              .search-input {
                color: #ffffff;

                &::placeholder {
                  color: rgba(142, 142, 147, 0.6);
                }
              }
            }
          }
        }

        .picker-wrapper {
          .picker-trigger {
            background: #2c2c2e;

            .picker-text {
              color: #ffffff;
            }
          }
        }
      }
    }
  }
}
</style>
